const svgCaptcha = require("svg-captcha");
const md5 = require("md5");
const Core = require("@alicloud/pop-core");
const db = require("../db");
const { changeObjType } = require("../utils");
const chalk = require("chalk");
const { server } = require("../project.config");
const jsonwebtoken = require("jsonwebtoken");
const xlsx = require("node-xlsx").default;
const fs = require("fs");
const path = require("path");

// 定义全局的验证码变量 code
let code = "";
let timer = null;
let time; // 有效时间300秒

exports.entryPwd = async (req, res) => {
  let { phoneNumber, password } = req.body;
  let selectResult = await sleectUser(phoneNumber);
  if (selectResult.length == 0) {
    // 新增注册
    let sql = "insert into users set ?";
    let sqlVal = { ...changeObjType(req.body, "h") };
    db.query(sql, sqlVal, async (err, result) => {
      if (err) return res.cc(err);
      if (result.affectedRows !== 1) return res.cc("系统错误");
      let selectResult = await sleectUser(phoneNumber);
      let secretData = { ...selectResult };
      delete secretData.password;
      let token = jsonwebtoken.sign(secretData, server.tokenSecretKey, {
        expiresIn: "7d",
      });
      res.send({
        code: 200,
        msg: "注册账户成功",
        data: "Bearer " + token,
      });
    });
  } else {
    // 验证密码
    if (selectResult[0].password !== password) {
      return res.send({
        code: 400,
        errorPwd: true,
        msg: "密码错误",
      });
    }
    let secretData = { ...selectResult };
    delete secretData.password;
    let token = jsonwebtoken.sign(secretData, server.tokenSecretKey, {
      expiresIn: "7d",
    });
    code = "";
    res.send({
      code: 200,
      msg: "登录成功",
      data: "Bearer " + token,
    });
  }

  function sleectUser(phoneNumber) {
    return new Promise((resolve, reject) => {
      let sql = "select * from users where phone_number=? and status=1";
      db.query(sql, [phoneNumber], (err, result) => {
        if (err) return reject(err);
        resolve(result);
      });
    }).catch((err) => {
      console.log(chalk.red(err));
    });
  }
};

exports.getSvgCaptcha = (req, res) => {
  const captcha = svgCaptcha.create({
    size: 4, //验证码长度
    noise: 4, //干扰线条数目
    width: 120, //宽度
    height: 38, //高度
    inverse: false, // 翻转颜色
    fontSize: 55, // 字体大小
    color: true, // 验证码字符颜色（需设置背景色）
    background: "#ccc", // 背景
  });
  code = captcha.text; // 存储验证码数值（这里使用变量来存储生成的验证码，其实可以使用session来进行存储）
  res.send({
    code: 200,
    data: {
      svg: captcha.data,
      code,
    },
  });
};

exports.sendMsg = (req, res) => {
  code = "";
  timer = null;
  time = 300;
  for (let i = 0; i < 6; i++) {
    code += Math.floor(Math.random() * 10);
  }
  var client = new Core({
    accessKeyId: "LTAI5t7sBt8xk1NrVu2EyzZa",
    accessKeySecret: "xDCWq5K2lMuDUTtCUG03puvwqdkNzk",
    // securityToken: '<your-sts-token>', // use STS Token
    endpoint: "https://dysmsapi.aliyuncs.com",
    apiVersion: "2017-05-25",
  });

  var params = {
    PhoneNumbers: req.body.phoneNumber, //接收短信的手机号码
    SignName: "玖天web学习个人博客", //短信签名名称
    TemplateCode: "SMS_268711112", //短信模板CODE
    TemplateParam: JSON.stringify({
      code,
    }),
  };

  var requestOption = {
    method: "POST",
  };

  client.request("SendSms", params, requestOption).then(
    (result) => {
      timer = setInterval(() => {
        if (time < 0) {
          code = "";
          time = null;
        }
        time--;
      }, 1000);
      res.send({
        code: 200,
        msg: "短信发送成功",
        data: null,
      });
    },
    (ex) => {
      res.cc(ex);
    }
  );
};

exports.entryPhone = async (req, res) => {
  let { phoneNumber, smsCode } = req.body;
  if (smsCode !== code)
    return res.send({
      code: 400,
      error: true,
      msg: "验证码不正确",
    });
  let selectResult = await sleectUser(phoneNumber);
  if (selectResult.length == 0) {
    // 新增注册
    let sql = "insert into users set ?";
    let sqlVal = { phone_number: phoneNumber };
    db.query(sql, sqlVal, async (err, result) => {
      if (err) return res.cc(err);
      if (result.affectedRows !== 1) return res.cc("系统错误");
      let selectResult = await sleectUser(phoneNumber);
      let secretData = { ...selectResult };
      delete secretData.password;
      let token = jsonwebtoken.sign(secretData, server.tokenSecretKey, {
        expiresIn: "7d",
      });
      res.send({
        code: 200,
        msg: "注册账户成功",
        data: "Bearer " + token,
      });
    });
  } else {
    // 响应token
    let secretData = { ...selectResult };
    delete secretData.password;
    let token = jsonwebtoken.sign(secretData, server.tokenSecretKey, {
      expiresIn: "7d",
    });
    code = "";
    res.send({
      code: 200,
      msg: "登录成功",
      data: "Bearer " + token,
    });
  }

  function sleectUser(phoneNumber) {
    return new Promise((resolve, reject) => {
      let sql = "select * from users where phone_number=? and status=1";
      db.query(sql, [phoneNumber], (err, result) => {
        if (err) return reject(err);
        resolve(result);
      });
    }).catch((err) => {
      console.log(chalk.red(err));
    });
  }
};

exports.resetPwd = (req, res) => {
  let { phoneNumber, password } = req.body;
  let sql = "update users set password=? where phone_number=? and status=1";
  db.query(sql, [password, phoneNumber], (err, result) => {
    if (err) return res.cc(err);
    if (result.affectedRows !== 1) return res.cc("系统错误");
    res.send({
      code: 200,
      msg: "重置密码成功",
      data: null,
    });
  });
};

/**
 * @description 注释 测试生成文件流
 */

exports.getXlsx = (req, res) => {
  const data = [
    {
      name: "firstSheet",
      data: [
        [1, 2, 3],
        [4, 5, 6],
      ],
    },
    {
      name: "secondSheet",
      data: [
        [7, 8, 9],
        [10, 1, 12],
      ],
    },
  ];
  // fs.writeFileSync(
  //   path.resolve(__dirname, "../blogServe/doc/lls.xlsx"),
  //   xlsx.build(data),
  //   "binary"
  // );
  res.send(xlsx.build(data));
  // res.send({
  //   path: `http://127.0.0.1:8520/blogServe/doc/lls.xlsx`,
  //   file: xlsx.build(data),
  // });
};
